package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {
    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private CommentApi commentApi;

    public UserInfoVo findUserInfoByHuanxin(String huanxinId) {
        Long userId = Long.valueOf(huanxinId.substring(2));
        UserInfo userInfo = userInfoApi.findById(userId);
        UserInfoVo vo = new UserInfoVo();
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfo, vo);
            vo.setAge(userInfo.getAge() + "");
        }
        return vo;
    }

    public void contacts(Long friendId) {
        Long userId = UserHolder.getId();
        friendApi.save(userId, friendId);
        huanXinTemplate.contactUsers(Constants.HX_USER_PREFIX + userId, Constants.HX_USER_PREFIX + friendId);
    }

    public PageResult contactList(Integer page, Integer pagesize, String keyword) {
        Long userId = UserHolder.getId();
        List<Friend> friendList = friendApi.findByUserId(userId);
        List<Long> friendIds = CollUtil.getFieldValues(friendList, "friendId", Long.class);
        Page<UserInfo> pageInfo = new Page<>(page, pagesize);
        pageInfo = userInfoApi.findFriendByPage(pageInfo, friendIds, keyword);
        List<UserInfo> userInfos = pageInfo.getRecords();
        List<ContactVo> voList = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            ContactVo vo = ContactVo.init(userInfo);
            voList.add(vo);
        }
        return new PageResult(page.longValue(), pagesize.longValue(), pageInfo.getTotal(), voList);
    }

}
